/**
 * Node Server Configuration
 */
'use strict';

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

// Module dependencies.
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
var redisClient = require('redis').createClient(config.redis.port, config.redis.host);

// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
if ('development' === process.env.NODE_ENV) {
    mongoose.set('debug', true);
}
// Verify database connection
mongoose.connection.on('connected', function () {
    console.log('MongoDB Connection Success!');
});

mongoose.connection.on('error', function () {
    throw 'MongoDB Connection Error. Please make sure MongoDB is running.';
});

// Setup server
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io')(server, {
    serveClient: (config.env !== 'production'),
    path: '/socket.io-client'
});
// Express configuration
require('./config/express')(app);
require('./config/socketio')(socketio, app.get("sessionStore"));
require('./routes')(app);

//
app.set('io', socketio);
app.set('redis', redisClient);

// Start Express server.
server.listen(config.port, config.ip, function () {
    console.log('fxz-ask server listening on port %d in %s mode', config.port, app.get('env'));
});

// Expose app
exports = module.exports = app;
